package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.config.OperationLog;
import com.zhentao.pojo.TcUser;
import com.zhentao.pojo.WxUser;
import com.zhentao.service.TcUserService;
import com.zhentao.config.Result;
import com.zhentao.config.TokenUtil;
import com.zhentao.config.PageResult;
import com.zhentao.service.WxService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("tea/user")
@Validated
public class UserController {

    @Autowired
    TcUserService userService;

    @Autowired
    WxService wxService;

    /**
     * 获取全部用户
     */
    @PostMapping("list")
    public Result<List<WxUser>> list(){
        try {
            List<WxUser> users = wxService.list();
            return Result.success("获取用户列表成功", users);
        } catch (Exception e) {
            return Result.error("获取用户列表失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID获取用户详情
     */
    @PostMapping("get/{id}")
    public Result<WxUser> getById(@PathVariable Integer id){
        try {
            WxUser user = wxService.getById(id);
            if (user != null) {
                return Result.success("获取用户详情成功", user);
            } else {
                return Result.error("用户不存在");
            }
        } catch (Exception e) {
            return Result.error("获取用户详情失败：" + e.getMessage());
        }
    }

    /**
     * 添加用户
     */
    @PostMapping("add")
    public Map<String, Object> add(@Valid @RequestBody TcUser user){
        Map<String, Object> result = new HashMap<>();
        try {
            user.setCreateTime(new Date());
            user.setUpdateTime(new Date());
            boolean success = userService.save(user);
            result.put("success", success);
            result.put("message", success ? "添加成功" : "添加失败");
            if (success) {
                result.put("data", user);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "添加失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 更新用户
     */
    @PutMapping("update")
    public Map<String, Object> update(@Valid @RequestBody TcUser user){
        Map<String, Object> result = new HashMap<>();
        try {
            user.setUpdateTime(new Date());
            boolean success = userService.updateById(user);
            result.put("success", success);
            result.put("message", success ? "更新成功" : "更新失败");
            if (success) {
                result.put("data", user);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 删除用户
     */
    @DeleteMapping("delete/{id}")
    public Map<String, Object> delete(@PathVariable Integer id){
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = userService.removeById(id);
            result.put("success", success);
            result.put("message", success ? "删除成功" : "删除失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 根据身份类型获取用户
     */
    @PostMapping("byIdentity/{identity}")
    public Result<List<WxUser>> getByIdentity(@PathVariable String identity){
        try {
            QueryWrapper<WxUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("identity", identity);
            queryWrapper.orderByDesc("create_time");
            List<WxUser> users = wxService.list(queryWrapper);
            return Result.success("根据身份获取用户成功", users);
        } catch (Exception e) {
            return Result.error("根据身份获取用户失败：" + e.getMessage());
        }
    }

    /**
     * 根据手机号获取用户
     */
    @PostMapping("byPhone/{phone}")
    public Result<WxUser> getByPhone(@PathVariable String phone){
        try {
            QueryWrapper<WxUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone", phone);
            WxUser user = wxService.getOne(queryWrapper);
            if (user != null) {
                return Result.success("根据手机号获取用户成功", user);
            } else {
                return Result.error("用户不存在");
            }
        } catch (Exception e) {
            return Result.error("根据手机号获取用户失败：" + e.getMessage());
        }
    }

    /**
     * 搜索用户
     */
    @PostMapping("search")
    public Result<List<WxUser>> searchUsers(@RequestParam String keyword){
        try {
            QueryWrapper<WxUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("nickname", keyword).or().like("phone", keyword);
            queryWrapper.orderByDesc("create_time");
            List<WxUser> users = wxService.list(queryWrapper);
            return Result.success("搜索用户成功", users);
        } catch (Exception e) {
            return Result.error("搜索用户失败：" + e.getMessage());
        }
    }

    /**
     * 获取老师列表
     */
    @PostMapping("teachers")
    public Result<List<WxUser>> getTeachers(){
        try {
            QueryWrapper<WxUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("identity", "老师");
            queryWrapper.orderByDesc("create_time");
            List<WxUser> teachers = wxService.list(queryWrapper);
            return Result.success("获取老师列表成功", teachers);
        } catch (Exception e) {
            return Result.error("获取老师列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取学生列表
     */
    @PostMapping("students")
    public Result<List<WxUser>> getStudents(){
        try {
            QueryWrapper<WxUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("identity", "学生");
            queryWrapper.orderByDesc("create_time");
            List<WxUser> students = wxService.list(queryWrapper);
            return Result.success("获取学生列表成功", students);
        } catch (Exception e) {
            return Result.error("获取学生列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取家长列表
     */
    @PostMapping("parents")
    public Result<List<WxUser>> getParents(){
        try {
            QueryWrapper<WxUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("identity", "家长");
            queryWrapper.orderByDesc("create_time");
            List<WxUser> parents = wxService.list(queryWrapper);
            return Result.success("获取家长列表成功", parents);
        } catch (Exception e) {
            return Result.error("获取家长列表失败：" + e.getMessage());
        }
    }

    /**
     * 批量删除用户
     */
    @DeleteMapping("batchDelete")
    public Map<String, Object> batchDelete(@RequestBody List<Integer> ids){
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = userService.removeByIds(ids);
            result.put("success", success);
            result.put("message", success ? "批量删除成功" : "批量删除失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "批量删除失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 更新用户头像
     */
    @PutMapping("updateAvatar/{id}")
    public Map<String, Object> updateAvatar(@PathVariable Integer id, @RequestParam String avatar){
        Map<String, Object> result = new HashMap<>();
        try {
            WxUser user = wxService.getById(id);
            if (user != null) {
                user.setAvatar(avatar);
                user.setUpdateTime(new Date());
                boolean success = wxService.updateById(user);
                result.put("success", success);
                result.put("message", success ? "头像更新成功" : "头像更新失败");
            } else {
                result.put("success", false);
                result.put("message", "用户不存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "头像更新失败：" + e.getMessage());
        }
        return result;
    }


    /**
     * 用户注册
     */
    @PostMapping("register")
    @OperationLog(value = "用户注册", type = "注册", module = "用户管理")
    public Result<TcUser> register(@Valid @RequestBody TcUser user) {
        try {
            // 检查手机号是否已存在
            QueryWrapper<TcUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone", user.getPhone());
            TcUser existingUser = userService.getOne(queryWrapper);
            
            if (existingUser != null) {
                return Result.error("手机号已存在");
            }
            
            user.setCreateTime(new Date());
            user.setUpdateTime(new Date());
            boolean success = userService.save(user);
            
            if (success) {
                return Result.success("注册成功", user);
            } else {
                return Result.error("注册失败");
            }
        } catch (Exception e) {
            return Result.error("注册失败：" + e.getMessage());
        }
    }


    /**
     * 修改密码（通过手机号）
     */
    @PutMapping("changePassword")
    public Result<String> changePassword(@RequestParam String phone, @RequestParam String newPassword) {
        try {
            QueryWrapper<TcUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone", phone);
            TcUser user = userService.getOne(queryWrapper);
            
            if (user != null) {
                // 这里可以添加密码加密逻辑
                user.setUpdateTime(new Date());
                boolean success = userService.updateById(user);
                
                if (success) {
                    return Result.success("密码修改成功");
                } else {
                    return Result.error("密码修改失败");
                }
            } else {
                return Result.error("用户不存在");
            }
        } catch (Exception e) {
            return Result.error("密码修改失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户统计信息
     */
    @PostMapping("statistics")
    public Result<Map<String, Object>> getUserStatistics() {
        try {
            Map<String, Object> statistics = new HashMap<>();
            
            // 总用户数
            long totalUsers = userService.count();
            statistics.put("totalUsers", totalUsers);
            
            // 各身份用户数
            QueryWrapper<TcUser> teacherQuery = new QueryWrapper<>();
            teacherQuery.eq("identity", "老师");
            long teacherCount = userService.count(teacherQuery);
            statistics.put("teacherCount", teacherCount);
            
            QueryWrapper<TcUser> studentQuery = new QueryWrapper<>();
            studentQuery.eq("identity", "学生");
            long studentCount = userService.count(studentQuery);
            statistics.put("studentCount", studentCount);
            
            QueryWrapper<TcUser> parentQuery = new QueryWrapper<>();
            parentQuery.eq("identity", "家长");
            long parentCount = userService.count(parentQuery);
            statistics.put("parentCount", parentCount);
            
            return Result.success("获取统计信息成功", statistics);
        } catch (Exception e) {
            return Result.error("获取统计信息失败：" + e.getMessage());
        }
    }

    /**
     * 分页查询用户
     */
    @PostMapping("page")
    public Result<PageResult<TcUser>> getUserPage(@RequestParam(defaultValue = "1") Integer current,
                                                  @RequestParam(defaultValue = "10") Integer size,
                                                  @RequestParam(required = false) String keyword,
                                                  @RequestParam(required = false) String identity) {
        try {
            Page<TcUser> page = new Page<>(current, size);
            QueryWrapper<TcUser> queryWrapper = new QueryWrapper<>();
            
            // 关键词搜索
            if (keyword != null && !keyword.trim().isEmpty()) {
                queryWrapper.like("name", keyword).or().like("phone", keyword);
            }
            
            // 身份筛选
            if (identity != null && !identity.trim().isEmpty()) {
                queryWrapper.eq("identity", identity);
            }
            
            queryWrapper.orderByDesc("create_time");
            
            Page<TcUser> result = userService.page(page, queryWrapper);
            
            PageResult<TcUser> pageResult = PageResult.of(
                (int) result.getCurrent(),
                (int) result.getSize(),
                result.getTotal(),
                result.getRecords()
            );
            
            return Result.success("分页查询成功", pageResult);
        } catch (Exception e) {
            return Result.error("分页查询失败：" + e.getMessage());
        }
    }

    /**
     * 分页查询老师
     */
    @PostMapping("teachers/page")
    public Result<PageResult<TcUser>> getTeachersPage(@RequestParam(defaultValue = "1") Integer current,
                                                      @RequestParam(defaultValue = "10") Integer size,
                                                      @RequestParam(required = false) String keyword) {
        try {
            Page<TcUser> page = new Page<>(current, size);
            QueryWrapper<TcUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("identity", "老师");
            
            if (keyword != null && !keyword.trim().isEmpty()) {
                queryWrapper.like("name", keyword).or().like("phone", keyword);
            }
            
            queryWrapper.orderByDesc("create_time");
            
            Page<TcUser> result = userService.page(page, queryWrapper);
            
            PageResult<TcUser> pageResult = PageResult.of(
                (int) result.getCurrent(),
                (int) result.getSize(),
                result.getTotal(),
                result.getRecords()
            );
            
            return Result.success("分页查询老师成功", pageResult);
        } catch (Exception e) {
            return Result.error("分页查询老师失败：" + e.getMessage());
        }
    }

    /**
     * 分页查询学生
     */
    @PostMapping("students/page")
    public Result<PageResult<WxUser>> getStudentsPage(@RequestParam(defaultValue = "1") Integer current,
                                                      @RequestParam(defaultValue = "10") Integer size,
                                                      @RequestParam(required = false) String keyword) {
        try {
            Page<WxUser> page = new Page<>(current, size);
            QueryWrapper<WxUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("identity", "学生");
            
            if (keyword != null && !keyword.trim().isEmpty()) {
                queryWrapper.like("name", keyword).or().like("phone", keyword);
            }
            
            queryWrapper.orderByDesc("create_time");
            
            Page<WxUser> result = wxService.page(page, queryWrapper);
            
            PageResult<WxUser> pageResult = PageResult.of(
                (int) result.getCurrent(),
                (int) result.getSize(),
                result.getTotal(),
                result.getRecords()
            );
            
            return Result.success("分页查询学生成功", pageResult);
        } catch (Exception e) {
            return Result.error("分页查询学生失败：" + e.getMessage());
        }
    }
}
